package com.ldj.rocketmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * User: ldj
 * Date: 2023/5/2
 * Time: 12:13
 * Description: 生产者
 */
@Slf4j
@Component
public class MyProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //发送普通消息
    public void sendMessages(String topic, String messages) {
        rocketMQTemplate.convertAndSend(topic, messages);
    }

    //发送事务消息
    public void sendMessagesInTransaction(String topic, String messages) throws InterruptedException {
        String[] tags = new String[]{"Tag1", "Tag2", "Tag3", "Tag4", "Tag5"};
        for (int i = 0; i < 10; i++) {
            Message<String> message = MessageBuilder.withPayload(messages).build();
            //topic+tag
            String destination = topic + ":" + tags[i % tags.length];
            //第一个destination消息要发往的目的地,第二个destination消息业务携带的数据
            TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(destination, message, destination);
            log.info(sendResult.toString());
            TimeUnit.MILLISECONDS.sleep(10);
        }
    }

}
